package com.anpy.common.service.utils;

import com.alibaba.fastjson2.JSON;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TokenUtils {
	
	public static String publicKey = "ijx-teacher";
	
	/**
	 * byte 数组转字符串
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
		}
		return hs.toUpperCase();
	}
	/**
	 * 字符串转byte数组
	 * @param hex
	 * @return
	 */
	private static byte[] hex2byte(String hex) {
		if(hex == null || hex.isEmpty() || hex.length() % 2 != 0){
			return new byte[0];
		}
		byte[] ret = new byte[hex.length() / 2];
		byte[] tmp = hex.getBytes();
		for (int i = 0; i < hex.length() / 2; i++) {
			ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
		}
		return ret;
	}
	/**
	 * 两个数组合并
	 * @param src0
	 * @param src1
	 * @return
	 */
	private static byte uniteBytes(byte src0, byte src1) {
		byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();
		_b0 = (byte) (_b0 << 4);
		byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();
		byte ret = (byte) (_b0 ^ _b1);
		return ret;
	}
	/**
	 * 根据内容 生成一个 外部访问 token
	 * @param content
	 * @return
	 */
	public static String createLinkToken(String content) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );  
	        secureRandom.setSeed(publicKey.getBytes("UTF-8"));  
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec secKey = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = content.getBytes("UTF-8");
			cipher.init(Cipher.ENCRYPT_MODE, secKey);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			String rsString = byte2hex(result).replaceAll("A", "-");
			return rsString;
		} catch (Exception e) {
		}
		return null;
	}
	/**
	 * 根据token 解析外部链接token里面的内容
	 */
	public static String parseLinkToken(String token) {
		try {
			token = token.replaceAll("-", "A");
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );  
	        secureRandom.setSeed(publicKey.getBytes("UTF-8"));
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec secKey = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, secKey);// 初始化
			byte[] hexByte = hex2byte(token);
			byte[] result = cipher.doFinal(hexByte);
			return new String(result, "UTF-8"); // 加密
		} catch (Exception e) {
		}
		return null;
	}
	public static void main(String[] args) {
//		AppToken appToken = new AppToken();
//		appToken.setUserId(222);
//		appToken.setType(1);
//		appToken.setTokenDate(System.currentTimeMillis());
//		String json = JSON.toJSONString(appToken, true);
//		System.out.println("json="+json);
//		String token = "FD-654-CC94-6+08+58-9CF3046--F+08D+BC82F78089F9+B71F2C9C71674-5D8674F982-5681F9+8B3643DD9949+09C5C426+1807-1+743F3457-1F44-60-+B";//TokenUtils.createToken(json);
//		System.out.println("token="+token);
//		String decodeStr = TokenUtils.parseToken(token);
//		System.out.println("detoken="+decodeStr);
//		AppToken appToken2 = JSON.parseObject(decodeStr, AppToken.class);
//		String key = appToken.getUserId()+"."+appToken2.getType();
//		System.out.println("key="+key);
	
//		String mm = TokenUtils.createLinkToken("3290");
//		System.out.println(mm);
//		String nn = TokenUtils.parseLinkToken(mm);
//		System.out.println(nn);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("schoolId", 2271);
		List<Map<String,Object>> l = new ArrayList<Map<String,Object>>();
		Map<String,Object> m = new HashMap<String, Object>();
		m.put("telNum", "15225746488");
		m.put("teacherName", "张小凡2");
		l.add(m);
		map.put("teachers", l);
		String finalStr = JSON.toJSONString(map);

		String mm = TokenUtils.createLinkToken(finalStr);
		System.out.println(mm);
		String nn = TokenUtils.parseLinkToken(mm);
		System.out.println(nn);
	}
}
